package com.smartinput.security

import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.beans.factory.annotation.Value
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import org.slf4j.LoggerFactory
import jakarta.annotation.PostConstruct

@Component
class JwtAuthenticationFilter(
    private val jwtService: JwtService,
    private val userDetailsService: CustomUserDetailsService,
    private val urlPatternMatcher: UrlPatternMatcher
) : OncePerRequestFilter() {

    private val logger=LoggerFactory.getLogger(JwtAuthenticationFilter::class.java)

    @Value("\${jwt.filter.skip-patterns}")
    private lateinit var skipPatterns: String

    @PostConstruct
    fun init() {
        logger.info("JWT过滤器初始化，跳过模式配置: $skipPatterns")
    }

    override fun doFilterInternal(
        request: HttpServletRequest,
        response: HttpServletResponse,
        filterChain: FilterChain
    ) {
        // 检查是否需要跳过JWT验证
        val requestURI = request.requestURI
        logger.debug("=== JWT过滤器开始处理请求: $requestURI ===")
        
        if (urlPatternMatcher.shouldSkipJwtValidation(requestURI, skipPatterns)) {
            logger.debug("跳过JWT验证: $requestURI (匹配配置模式)")
            filterChain.doFilter(request, response)
            return
        }
        
        val authHeader = request.getHeader("Authorization")
        logger.debug("请求URI: $requestURI, Authorization头: ${authHeader?.let { it.take(50) } ?: "null"}...")
        
        if (authHeader == null || !authHeader.startsWith("Bearer ") || authHeader.length <= 7) {
            logger.debug("缺少或无效的Authorization头")
            filterChain.doFilter(request, response)
            return
        }

        val jwt = authHeader.substring(7)
        val userId = jwtService.getUserIdFromToken(jwt)
        logger.debug("JWT解析，用户ID: $userId")
        
        if (userId != null && SecurityContextHolder.getContext().authentication == null) {
            try {
                logger.debug("JWT验证，用户ID: $userId")
                val userDetails = userDetailsService.loadUserById(userId)
                logger.debug("用户详情加载成功: ${userDetails.username}")
                if (jwtService.validateToken(jwt)) {
                    val authToken = UsernamePasswordAuthenticationToken(
                        userId, // 使用userId作为principal
                        null,
                        userDetails.authorities
                    )
                    SecurityContextHolder.getContext().authentication = authToken
                    logger.debug("JWT验证成功，设置认证信息")
                } else {
                    logger.debug("JWT token验证失败")
                }
            } catch (e: Exception) {
                // 如果用户不存在，记录日志但不阻止请求继续
                logger.debug("JWT验证失败: ${e.message}")
                e.printStackTrace()
            }
        } else {
            logger.debug("JWT验证跳过: userId=$userId, 已有认证=${SecurityContextHolder.getContext().authentication != null}")
        }
        
        logger.debug("=== JWT过滤器处理完成，继续过滤器链 ===")
        filterChain.doFilter(request, response)
    }
} 